import random
from tencentcloud.common import credential
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
from tencentcloud.sms.v20210111 import sms_client, models
from tencentcloud.common.profile.client_profile import ClientProfile
from tencentcloud.common.profile.http_profile import HttpProfile
from utils.luffy_logging import logger
from . import settings


def get_code(count=4):
    code_str = ''
    for i in range(count):
        num = random.randint(0, 9)
        code_str += str(num)

    return code_str


def send_sms(phone, code):
    try:
        cred = credential.Credential(settings.SECRETID, settings.SECRETKEY)
        httpProfile = HttpProfile()

        httpProfile.reqMethod = "POST"  # post请求(默认为post请求)
        httpProfile.reqTimeout = 30  # 请求超时时间，单位为秒(默认60秒)
        httpProfile.endpoint = "sms.tencentcloudapi.com"  # 指定接入地域域名(默认就近接入)
        clientProfile = ClientProfile()
        clientProfile.signMethod = "TC3-HMAC-SHA256"  # 指定签名算法
        clientProfile.language = "en-US"
        clientProfile.httpProfile = httpProfile
        client = sms_client.SmsClient(cred, "ap-guangzhou", clientProfile)
        req = models.SendSmsRequest()
        req.SmsSdkAppId = settings.APPID
        req.SignName = settings.SIGNNAME
        req.TemplateId = settings.TEMPLATEID
        req.TemplateParamSet = [code, "5"]
        req.PhoneNumberSet = ["+86%s" % phone, ]
        req.SessionContext = ""
        req.ExtendCode = ""
        req.SenderId = ""
        client.SendSms(req)
        # print(resp.to_json_string(indent=2))
        return True
    except TencentCloudSDKException as err:
        # 如果短信发送失败 记录日志 如果给别人使用 需要修改
        logger.error("手机号为: %s 发送短信失败，失败原因: %s" %(phone,str(err)))


if __name__ == '__main__':
    print(get_code())
